package com.bw.controller;

import com.bw.bean.Dianpu;
import com.bw.service.DianpuService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.util.StringUtil;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

@Controller
public class DianpuController {
    @Resource
    private DianpuService dianpuService;
    @RequestMapping("list")
    public String list(
            Model model, Dianpu dianpu,
            @RequestParam(defaultValue = "1")int pageNum,
            @RequestParam(defaultValue = "3")int pageSize){
        PageHelper.startPage(pageNum,pageSize);
        List<Dianpu> list = dianpuService.list(dianpu);
        PageInfo<Dianpu> pageInfo = new PageInfo<>(list);
        model.addAttribute("dianpu",dianpu);
        model.addAttribute("pageInfo",pageInfo);
        return "list";
    }

    @RequestMapping("toadd")
    public String toadd(String did,Model model){
        if(StringUtil.isNotEmpty(did)){
            Dianpu getid = dianpuService.getid(did);
            model.addAttribute("getid",getid);
        }
        return "add";
    }
    @RequestMapping("xq")
    public String xq(String did,Model model){
        Dianpu getid = dianpuService.getid(did);
        model.addAttribute("getid",getid);
        return "xq";
    }
    @RequestMapping("save")
    @ResponseBody
    public String save(Dianpu dianpu,MultipartFile file){
        if(file!=null && file.getSize()>0){
            String filename = file.getOriginalFilename();
            String substring = filename.substring(filename.lastIndexOf("."));
            String s = UUID.randomUUID().toString() + substring;
            try {
                file.transferTo(new File("D:\\PICTURE\\"+s));
                dianpu.setImg("/PICTURE/"+s);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        String did = dianpu.getDid();
        if(StringUtil.isNotEmpty(did)){
            dianpuService.update(dianpu);
        }else{
            dianpuService.insert(dianpu);
        }
        return "redirect:list.do";
    }
}
